<template>
  <div class="form-layout">
    <!--左侧导航-->
    <div class="nav-left">
      <customAnchor
        :itemList="[
          { name: 'box-base', title: '基础信息' },
           { name: 'box-dtl', title: '预算明细' },
        ]"
      />
    </div>
     <!--表单区域-->
     <div class="form-right" ref="formRight">
      <div id="box-base" class="box-title">基础信息</div>
      <customForm :data="form" :rules="propRules" ref="editForm" :disabled="propReadonly" :withRangeYMD="true">
        <template #content>
          <customFormItem label="业务单号" name="busKey" :parent="_self" :form="form" disabled :config="{defaultValue: '系统自动生成'}" />
          <customFormItem label="业务日期" name="busDate" :parent="_self" :form="form" disabled />
          <customFormItem
            label="填报科室"
            name="deptName"
            :parent="_self"
            :form="form"
            :readonly="true"
            :showSelectIcon="true"
            @focus="utilSelect.dept(selectDept)"
            :disabled="!propParent.cpFormNew"
          />
          <customFormItem label="年月" name="periodYearMonth" :parent="_self" :form="form"
            :type="constCommon.formItemType.datePicker.name" mode="month"
            @change="periodYearMonthChange"
          />
          <customFormItem
            label="期间"
            name="proid"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.slot.name"
          >
            <template #content>
              {{dates.formatToAnotherPattern(form.startDate, 'yyyy-MM-dd') }} ~ {{dates.formatToAnotherPattern(form.endDate, 'yyyy-MM-dd')}}
            </template>
          </customFormItem>

          <customFormItem
            :label="msgPre + '上年'"
            name="lastyaer"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.slot.name"
          >
            <template #content>
              <span style="color: red;margin-right: 8px;">限额: {{form.lastYearAmount}}</span>
              <span style="color: #ff8917;">限量: {{form.lastYearQty}}</span>
            </template>
          </customFormItem>

          <customFormItem
            :label="msgPre + '上月'"
            name="lastmonth"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.slot.name"
          >
            <template #content>
              <span style="color: red;margin-right: 8px;">限额: {{form.lastMonthAmount}}</span>
              <span style="color: #ff8917;">限量: {{form.lastMonthQty}}</span>
            </template>
          </customFormItem>

          <customFormItem
            :label="msgPre + '本月'"
            name="month"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.slot.name"
          >
            <template #content>
              <span style="color: red;margin-right: 8px;">消耗额: {{form.amountUseMonth}}</span>
              <span style="color: #ff8917;">消耗量: {{form.qtyUseMonth}}</span>
            </template>
          </customFormItem>

          <customFormItem label="是否限制全院" name="flagHospital" :parent="_self" :form="form"
            :type="constCommon.formItemType.switch.name"
            help="限制全院：则全院都将使用同样的限制"
            @change="flagHospitalChange"
          />

          <customFormItem label="操作人" name="busUser" :parent="_self" :form="form" disabled />
          <customFormItem label="备注" name="remark" :parent="_self" :form="form" />
        </template>
      </customForm>
      <div id="box-dtl" class="box-title">预算明细</div>
      <div class="budget-list"  v-show="!propParent.cpFormNew">
        <div class="budget-list-item">
          <h4>可以针对单个限额设置限制耗材列表</h4>
          <data-view
            propViewKey="dept_budget_item"
            ref="budgetItem"
            class="data-view-inlinebtn"
            @before-button-click="beforeButtonClickItem"
            @edit-input="editInput"
            @after-load="afterLoadItem"
            :propAutoFetchData="false"
            @current-change="handleCurrentRowChangeItem"
            @after-save="afterSaveItem"
            :propFlowKey="propParent.propFlowKey"
            :propParentPage="_self"
            :propInitData="form"
            :propHideFlowSelect="true"
          />
        </div>
        <div class="budget-list-item">
          <h4>请选择左侧需要设置限制耗材的记录</h4>
        <data-view
          propViewKey="dept_budget_matr"
          ref="budgetMatr"
          class="data-view-inlinebtn"
          @before-button-click="beforeButtonClickMatr"
          :propAutoFetchData="false"
          :propFlowKey="propParent.propFlowKey"
          :propParentPage="_self"
          :propInitData="form"
          :propHideFlowSelect="true"
        />
        </div>
      </div>
    </div>
      <!--模版商品选择-->
      <tableDrawer
      ref="matrName"
      refName="matrName"
      viewKey="matr_select_inorder"
      loadForce
      title="请选择需要的商品"
      subtitle="同一个预算单耗材不允许重复"
      :propUserParam="{sqlFilterMatr: getSqlFilterMatr()}"
      :widthPer="80"
      :heightPx="-1"
      :widthPx="-1"
    />
  </div>
</template>

<script>
import customAnchor from '@/components/custom/form/customAnchor.vue'

export default {
  data() {
    return {
      form: {},
      viewData: {},
      budgetItemIdSelect: null,
      budgetItemIndexSelect: '',
      budgetItemRowSelect: null,
      msgPre: '科室',
    }
  },
  computed: {
    cpBudgetWrapper() {
      let wrapper = this.$newWrapper()
      wrapper.eq('deptId', this.form.deptId)
      return wrapper
    },
  },
  methods: {
    // 选择需求科室
    selectDept(row) {
      this.$set(this.form, 'deptId', row.id)
      this.$set(this.form, 'deptName', row.name)
    },

     //年月变化后
     periodYearMonthChange() {
      if (this.form.periodYearMonth) {
        let periodYearMonth = new Date(this.form.periodYearMonth)
        this.$set(this.form, 'periodYearMonth', periodYearMonth.format(this.dates.defaultDateYMPattern))
        this.$set(this.form, 'startDate', this.dates.getFirstDayOfMonth(periodYearMonth).format(this.dates.defaultDatePattern))
        this.$set(this.form, 'endDate', this.dates.getLastDayOfMonth(periodYearMonth).format(this.dates.defaultDatePattern))
        this.$set(this.form, 'periodYear', this.form.periodYearMonth.split('-')[0])
        this.$set(this.form, 'periodMonth', this.form.periodYearMonth.split('-')[1])

        //获取 上年限额限量  上月限额限量 本月消耗额 消耗量
        this.$ajax.get(`/dept/budget/getQtyAmount?year=${this.form.periodYear}&month=${this.form.periodMonth}&startDate=${this.form.startDate}&endDate=${this.form.endDate}&flagHospital=${this.form.flagHospital}` ).then((response) => {
          console.log('getQtyAmount.response.data', response.data)
          if(response.code == 0 ){
            this.$set(this.form, 'amountUseMonth', response.data.amountUseMonth)
            this.$set(this.form, 'qtyUseMonth', response.data.qtyUseMonth)
            this.$set(this.form, 'lastYearAmount', response.data.lastYearAmount)
            this.$set(this.form, 'lastYearQty', response.data.lastYearQty)
            this.$set(this.form, 'lastMonthAmount', response.data.lastMonthAmount)
            this.$set(this.form, 'lastMonthQty', response.data.lastMonthQty)
          }
        })
      } else {
        this.$set(this.form, 'startDate', '')
        this.$set(this.form, 'endDate', '')
      }
    },

    //全院开关改变后
    flagHospitalChange() {
      this.msgPre = this.form.flagHospital ? '全院' : '科室'
      this.periodYearMonthChange()
    },

    //保存主表，如果没保存的话
    async saveMain (call,type) {
      if (!this.form.id) {
        await this.propParent.ocAsynSaveViewForm()
        if (!this.form.id) {
          this.utilMessage.warning('请先完成主单据必填项')
          return
        }
      }
      if (type && type == 'matr' && this.strings.isBlank(this.budgetItemIdSelect)) {
        this.utilMessage.warning('请选择左侧需要设置限制耗材的记录')
        return
      }
      call()
    },

    //明细视图点击前
    beforeButtonClickItem({btn, call}) {
      let pass = true
      if (btn.code == 'vb-add') { //添加前
        this.saveMain(() => {
          this.$refs.budgetItem.addnew()
        })
        call(false)
      }
    },
    //耗材视图点击前
    beforeButtonClickMatr({btn, call}) {
      if (btn.code == 'vb-add') { //添加前
        this.saveMain(() => {
          this.$refs.matrName.show(this.saveBatchItem, true)
          // this.
          // this.$refs.matrName.show()
        }, 'matr')
        call(false)
      }
    },

    // 添加预算明细
    saveBatchItem(matrList) {
      //主单据未保存
      if(this.propParent.cpFormNew) {
        this.propParent.ocAsynSaveViewForm(() => {
          this.selectChange(matrList)
        })
        return
      }
      this.selectChange(matrList)
    },

    //耗材选择后
    selectChange(matrList) {
      let rowsSave = []
      for (let i = 0; i < matrList.length; i++) {
        rowsSave.push(matrList[i])
        rowsSave[i].budgetId = this.form.id
        rowsSave[i].budgetItemId = this.budgetItemIdSelect
        rowsSave[i].matrId = rowsSave[i].id
        rowsSave[i].matrSpec = rowsSave[i].spec
        rowsSave[i].matrModel = rowsSave[i].model
      }

      //批量添加
      this.utilVue.loadShow(true)
      this.$ajax.post('/dept/budget_matr/saveBatchItemMatr', rowsSave).then(resp => {
        if (resp.code == 0) {
          this.utilMessage.success(resp.msg)
          this.fetchData('matr')
        }
        this.utilVue.loadHide()
      })
    },

    //明细行编辑
    editInput({row, column}) {
      this.$set(row, 'budgetId', this.form.id)
    },

    //加载左右网格数据
    fetchData(type) {
      let wrapperItem = this.$newWrapper()
      let wrapperMatr = this.$newWrapper()
      if (this.form.id) {
        wrapperItem.eq('budgetId', this.form.id)
        wrapperMatr.eq('budgetItemId', this.strings.defaultString(this.budgetItemIdSelect,'-1'))
      } else {
        wrapperItem.eq(1, 0)
        wrapperMatr.eq(1, 0)
      }

      if (type == 'item' || type =='all') {
        this.$refs.budgetItem.setQueryWrapper(wrapperItem)
        this.$refs.budgetItem.ocSetShowRadioBox(true)
      }
      if (type == 'matr' || type =='all') this.$refs.budgetMatr.setQueryWrapper(wrapperMatr)
    },

    //明细行选中
    handleCurrentRowChangeItem(param) {
      if (param == null) {
        this.budgetItemIdSelect = null
        this.budgetItemIndexSelect = ''
        this.budgetItemRowSelect = null
        return
      }
      this.budgetItemIdSelect = param.row.row.id
      this.budgetItemIndexSelect = param.row.seq
      this.budgetItemRowSelect = param.row
      this.$refs.budgetItem.$refs.tbMain.setRadioRow(param.row.row)
      this.fetchData('matr')
    },

    afterSaveItem(row) {
      this.handleCurrentRowChangeItem({
        row: {
          row: row,
          seq: 1
        }
      })
    },

    afterLoadItem () {
      this.handleCurrentRowChangeItem(null)
      this.fetchData('matr')
    },
    getSqlFilterMatr() {
      if (!this.form || !this.form.id) return
      return   ` and id not in (select matr_id from dept_budget_matr where  budget_id = '${this.form.id}' )`
    }
  },
  created() {
    let that = this
    this.$emit('event-register', {
      validate: (callback) => {
        return this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: (formData, initData) => {
        this.form = global.utils.jsonClone(formData)
        if (!this.form.id) {
          let dateNow = new Date()
          this.$set(this.form, 'busUser', this.utils.getCurrentUser().name)
          this.$set(this.form, 'busDate', dateNow.format(this.dates.defaultDatePattern))
          this.$set(this.form, 'periodYearMonth', dateNow.format(this.dates.defaultDateYMPattern))
          this.$set(this.form, 'lastYearAmount', 0)
          this.$set(this.form, 'lastYearQty', 0)
          this.$set(this.form, 'lastMonthAmount', 0)
          this.$set(this.form, 'lastMonthQty', 0)
          this.$set(this.form, 'lastYearAmount', 0)
          this.$set(this.form, 'amountUseMonth', 0)
          this.$set(this.form, 'qtyUseMonth', 0)
          this.$set(this.form, 'flagHospital', false)
          //默认为上月的限额
          this.periodYearMonthChange()
        }
        this.fetchData('all')
      },
      afterSave: () => {  },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {
      },
      beforeFlow: (flowButtonKey) => {
        return true
      },
      afterFlow: (flowButtonKey) => {
      },
      beforeClose: () => {
        return true
      },
      afterClick(button, data, viewForm) {
        let {key: buttonKey} = button
        if (buttonKey == 'copy') { //复制
          that.$confirm('是否复制，包含主单据及相关明细?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'success'
          }).then(() => {
            that.utilVue.loadShow(true)
            that.$ajax.get(`/dept/budget/copy/${data.id}`).then(resp => {
              that.utilVue.loadHide()
              if (resp.code == 0) {
                that.propParent.ocRefresh()
                that.$confirm('复制成功，是否打开进行编辑?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'success'
                }).then(() => {
                  that.propParent.viewRow(resp.data.id)
                }).catch(() => {
                })
              }
            })
          }).catch(() => {
          })
        }
      }
    })
  },
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object
  },
  components: {
    customAnchor
  },
}
</script>
<style lang="scss" scoped>
  .budget-list {
    width: 100%;
    display: flex;
    justify-content: left;
    .budget-list-item{
     margin-right: 12px;
    }
  }
</style>
